package org.room402.chat.process;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.reactivestreams.Publisher;
import org.room402.constant.chat.MessageAction;
import org.room402.entity.chat.ChatPool;
import org.room402.entity.chat.MessageEvent;
import org.room402.entity.chat.UserSession;
import org.room402.framework.chat.container.ChatPoolContainer;
import org.room402.framework.chat.container.UserSessionContext;
import org.room402.utile.chat.FastChatUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class PoolCreateEventProcess implements MessageProcess {
    private final int maxPool = 5;

    private final ChatPoolContainer chatPoolContainer;
    private final UserSessionContext userSessionContext;

    @Override
    public boolean actionMatch(MessageEvent event, WebSocketSession session) {
        return MessageAction.pool_create.equals(event.getAction());
    }

    @Override
    public boolean rejectMatch(MessageEvent event, WebSocketSession session) {
        return maxPool < userSessionContext.getBySid(session.getId()).getCreatedPoolIds().size();
    }

    @Override
    public Publisher<Void> process(MessageEvent event, WebSocketSession session) {
        UserSession userSession = userSessionContext.validBySid(session.getId());
        ChatPool chatPool = chatPoolContainer.create(userSession, event.getContent());

        return Flux.fromIterable(chatPool.getMembers())
                .map(userInfoView -> userSessionContext.getByUid(userInfoView.getId()))
                .flatMap(poolUser -> {
                    MessageEvent messageEvent = MessageEvent.form(chatPool.getId(), poolUser.getId(), MessageAction.pool_update, chatPool);
                    return poolUser.getSession()
                            .send(Mono.just(poolUser.getSession().textMessage(JSONUtil.toJsonStr(messageEvent))));
                });

    }

    @Override
    public Publisher<Void> reject(MessageEvent event, WebSocketSession session) {
        UserSession userSession = userSessionContext.validBySid(session.getId());
        return FastChatUtil.reject(userSession, "您的聊天池已达上限，请解散无用聊天池再试,当前上限:" + maxPool);
    }
}
